package com.leyou.cart.service.impl;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.threadlocals.UserHolder;
import com.leyou.common.utils.JsonUtils;
import com.leyou.cart.entity.Cart;
import com.leyou.cart.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @author: wangzibeng
 * Date: 2019/5/18 0018
 * Time: 10:20
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final String KEY_PREFIX = "ly:cart:uid:";

    @Override
    public void addCart(Cart cart) {
        String key = KEY_PREFIX + UserHolder.getUser();
        // 获取hash操作的对象，并绑定用户id
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(key);
        // 获取skuId
        String skuId = cart.getSkuId().toString();
        // 获取数量
        Integer num = cart.getNum();
        Boolean aBoolean = ops.hasKey(skuId);
        //防止空指针
        if (aBoolean && aBoolean != null) {
            // 存在
            cart = JsonUtils.toBean(ops.get(skuId), Cart.class);
            // 修改数量
            cart.setNum(num + cart.getNum());
        }
        ops.put(skuId, JsonUtils.toString(cart));
    }

    @Override
    public List<Cart> queryCart() {
        // 获取登录用户名
        String key = KEY_PREFIX + UserHolder.getUser();
        // 判断redis key 是否存在
        Boolean aBoolean = stringRedisTemplate.hasKey(key);
        if (aBoolean == null || !aBoolean) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(key);
        Long size = ops.size();
        // 判断是否有数据
        if (size == null || size <= 0) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        return ops.values()
                .stream()
                .map(json -> JsonUtils.toBean(json, Cart.class))
                .collect(Collectors.toList());
    }

    @Override
    public void editCart(Long skuId, Integer num) {
        String key = KEY_PREFIX + UserHolder.getUser();
        // 获取hash操作的对象
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(key);
        String hashKey = skuId.toString();
        Boolean aBoolean = ops.hasKey(hashKey);
        if (aBoolean == null || !aBoolean) {
            log.error("购物车商品不存在 用户:{},商品:{}", UserHolder.getUser(), skuId);
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //查询购物车商品
        Cart cart = JsonUtils.toBean(ops.get(hashKey), Cart.class);
        cart.setNum(num);
        ops.put(hashKey, JsonUtils.toString(cart));
    }

    @Override
    public void deleteCart(String skuId) {
        Long userId = UserHolder.getUser();
        String key = KEY_PREFIX + userId;
        Boolean aBoolean = stringRedisTemplate.hasKey(key);
        if (aBoolean == null || !aBoolean) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(key);
        Long delete = ops.delete(skuId);
        if (delete != 1) {
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }
    }

    @Override
    public void addCarts(List<Cart> carts) {
        String key = KEY_PREFIX + UserHolder.getUser();
        BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(key);
        for (Cart cart : carts) {
            Integer num = cart.getNum();
            String skuId = cart.getSkuId().toString();
            Boolean aBoolean = ops.hasKey(skuId);
            if (aBoolean != null || aBoolean) {
                cart = JsonUtils.toBean(ops.get(skuId), Cart.class);
                cart.setNum(cart.getNum() + num);
            }
            ops.put(skuId, JsonUtils.toString(cart));
        }
    }
}
